package org.wisdom.ac.apis.assembler;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.springframework.stereotype.Component;
import org.wisdom.ac.domain.resource.repository.ResourceRepository;
import org.wisdom.ac.domain.role.entity.AcRole;
import org.wisdom.ac.domain.role.entity.AcRoleResource;
import org.wisdom.ac.dto.RoleDto;
import org.wisdom.exception.BusinessException;

import cn.hutool.core.bean.BeanUtil;
import lombok.RequiredArgsConstructor;

/**
 * 系统角色组装器
 *
 * @author 张智研
 * @date 2022/05/23 13:59
 **/
@RequiredArgsConstructor
@Component
public class RoleAssembler {

    private final ResourceRepository resourceRepository;

    /**
     * dto转换为实体
     * 
     * @author 张智研
     * @date 2022/05/31 15:18
     * @param roleDto
     *            角色
     * @return org.wisdom.ac.domain.entity.AcRole
     */
    public AcRole roleDtoToEntity(RoleDto roleDto) {
        AcRole role = BeanUtil.copyProperties(roleDto, AcRole.class, "roleResources", "roleMenus");
        String[] roleResources = roleDto.getRoleResources() == null ? new String[0] : roleDto.getRoleResources();
        List<AcRoleResource> roleResourceList = new ArrayList<>();
        for (String roleResourceId : roleResources) {
            boolean isExists = this.resourceRepository.existsById(roleResourceId);
            if (!isExists) {
                throw new BusinessException("资源{" + roleResourceId + "}不存在!");
            }
            AcRoleResource roleResource = new AcRoleResource();
            roleResource.setResourceId(roleResourceId);
            roleResourceList.add(roleResource);
        }
        role.setRoleResources(roleResourceList);

        return role;
    }

    /**
     * 实体转换为dto
     * 
     * @author 张智研
     * @date 2022/05/31 15:22
     * @param role
     *            角色
     * @return org.wisdom.ac.dto.RoleDto
     */
    public RoleDto roleEntityToDto(AcRole role) {
        RoleDto roleDto = BeanUtil.copyProperties(role, RoleDto.class, "roleResources", "roleMenus");
        List<AcRoleResource> roleResourceList = role.getRoleResources();
        String[] roleResources = new String[roleResourceList.size()];
        int n = 0;
        for (AcRoleResource roleResource : roleResourceList) {
            roleResources[n++] = roleResource.getResourceId();
        }
        roleDto.setRoleResources(roleResources);
        return roleDto;
    }

    /**
     * entity列表转换为dto列表
     * 
     * @author 张智研
     * @date 2022/05/31 15:23
     * @param roleList
     *            角色列表
     * @return java.util.List<org.wisdom.ac.dto.RoleDto>
     */
    public List<RoleDto> roleEntityToDto(List<AcRole> roleList) {
        return roleList.stream().map(this::roleEntityToDto).collect(Collectors.toList());
    }

}
